# -*- coding: UTF-8 -*-

import requests
import json
import streamlit as st
import pandas as pd
import datetime

st.set_page_config(
        page_title="location",
        page_icon="✔",
        layout="centered",
        initial_sidebar_state="auto"
    )

def submit_loc():
    with st.spinner('打卡中...'):
        df = pd.read_excel('./output/打卡.xlsx')
        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        df_new = pd.DataFrame({'时间':time, '单位':company, '姓名':name, '纬度':lat, '经度':lon}, index=[0])
        df = pd.concat([df, df_new], axis=0, ignore_index=True)
        df.to_excel('./output/打卡.xlsx', index=False)
    st.success('打卡成功!')
    st.stop()

with st.spinner('定位中...'):
    url = "https://ip.cn/api/index?ip=&type=0"
    r = requests.get(url)
    ip = json.loads(r.text)["ip"]
    url_api = f'http://ip-api.com/json/{ip}?fields=status,message,country,countryCode,region,regionName,city,zip,lat,lon,timezone,isp,org,as,query&lang=zh-CN'
    r = requests.get(url_api)
    location = json.loads(r.text)
    lon, lat = location["lon"], location["lat"]
    df = pd.DataFrame([[lat, lon]], columns=['lat', 'lon'])

    # 高德API
    #key = '6619c5a3160ae2780d3dfd241ec16508'
    #url = "https://ip.cn/api/index?ip=&type=0"
    #r = requests.get(url)
    #ip = json.loads(r.text)["ip"]
    #url_api = f'https://restapi.amap.com/v3/ip?key={key}&ip={ip}'
    #r = requests.get(url_api)
    #location = json.loads(r.text)
    #lon, lat = location["rectangle"].split(';')[-2].split(',')[-2], location["rectangle"].split(';')[-2].split(',')[-1]
    #df = pd.DataFrame([[lat, lon]], columns=['lat', 'lon'], dtype='float')

with st.form('打卡'):
    col11, col22 = st.columns(2)
    with col22:
        st.write('您的位置:', lat, ',', lon)
    with col11:
        submit = st.form_submit_button(label='打卡')
    st.map(df)
    col1, col2 = st.columns(2)
    with col1:
        company = st.selectbox(label='您的单位:', options=('', '中通', '市工程', '中通建', '长讯'))
    with col2:
        name = st.text_input(label='您的姓名:', key=str)

    if submit:
        submit_loc()
        st.toast('打卡成功!')